package com.sctu.edu.tracks.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.sctu.edu.tracks.R;
import com.sctu.edu.tracks.adapter.RecordAdapter;
import com.sctu.edu.tracks.bean.RecordListBean;
import com.sctu.edu.tracks.config.URLConfig;
import com.sctu.edu.tracks.utils.L;
import com.sctu.edu.tracks.utils.httputils.GetVolleyHttp;

import java.util.List;

/**
 * Created by zhengsenwen on 2017/3/8.
 */

public class Fragment2 extends Fragment {

    private ListView listView;
    private List<RecordListBean.Data> list;
    private Activity activity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        activity = getActivity();
        View view = LayoutInflater.from(activity).inflate(R.layout.records_list, null);
        listView = (ListView) view.findViewById(R.id.records_list_listView);
        requestRecordsList();
        return view;
    }

    private void requestRecordsList() {
        Response.Listener<String> listener = new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {
                L.e("recordsList", json);
                RecordListBean recordListBean = JSON.parseObject(json, RecordListBean.class);
                if (200 == recordListBean.getCode()) {
                    Toast.makeText(activity, "请求成功", Toast.LENGTH_SHORT).show();
                    list = recordListBean.getData();
                    listView.setAdapter(new RecordAdapter(activity, list));
                } else {
                    Toast.makeText(activity, "网络出了点小问题", Toast.LENGTH_SHORT).show();
                }
            }
        };
        Response.ErrorListener errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                L.e("recordList", volleyError.getMessage() + "");
                Toast.makeText(activity, "网络出了点小问题", Toast.LENGTH_SHORT).show();
            }
        };
        GetVolleyHttp.getInstance(activity).getStringGETJsonData(
                URLConfig.URL_RECORDS, listener, errorListener, (long) 5000);
    }
}
